package com.greatwall.hip.cms.schedule;

import cn.hutool.core.date.*;
import cn.hutool.cron.CronUtil;
import com.greatwall.hip.cms.constant.MonitorPreCategoryEnum;
import com.greatwall.hip.cms.dao.LyDiseaseSymptomDao;
import com.greatwall.hip.cms.dao.LyDiseaseTagDao;
import com.greatwall.hip.cms.dao.LyPacsReportDao;
import com.greatwall.hip.cms.entity.LyPacsReport;
import com.greatwall.hip.cms.util.MonitorCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时查询当前一个月数据缓存，加速后续读取
 *
 * @author ljl
 * @date 2021/3/3 9:12
 **/
@Slf4j
@Component
public class MonitorPreLastMonthLoadSchedule implements CommandLineRunner {

    @Resource
    private LyDiseaseTagDao lyDiseaseTagDao;

    @Resource
    private LyPacsReportDao lyPacsReportDao;

    @Resource
    private LyDiseaseSymptomDao lyDiseaseSymptom;

    @Override
    public void run(String... args) throws Exception {
//        CronUtil.schedule(preLoadCron, (cn.hutool.cron.task.Task) this::initLastMonthData);
//        CronUtil.setMatchSecond(true);
//        CronUtil.start(true);

//        initLastMonthData();
    }

    public void initLastMonthData() {
        //清空数据
        MonitorCacheUtil.clear();

        //上个月日期, 七天为上个周期的七天
        DateTime lastMonDate = DateUtil.offset(DateUtil.yesterday(), DateField.DAY_OF_MONTH, -37);

        //遍历最近30天
        DateRange lastMonDateTimes = new DateRange(lastMonDate, DateUtil.yesterday(), DateField.DAY_OF_MONTH);
        lastMonDateTimes.forEach(dateTime -> {
            String date = dateTime.toString(DatePattern.PURE_DATE_PATTERN);
            MonitorCacheUtil.put(date, lyDiseaseTagDao.queryDiseaseByBetweenDate(date, date), MonitorPreCategoryEnum.DISEASE);
            MonitorCacheUtil.put(date, lyDiseaseSymptom.querySymptomByDate(date, date), MonitorPreCategoryEnum.SYMPTOM);

            List<LyPacsReport> pacsReports = lyPacsReportDao.queryAllByDate(date, date);
            List<LyPacsReport> childPacsReports = lyPacsReportDao.queryChildAllByDate(date, date);
            MonitorCacheUtil.put(date, pacsReports, MonitorPreCategoryEnum.PACS_REPORT_ABNORMAL);
            MonitorCacheUtil.put(date, childPacsReports, MonitorPreCategoryEnum.CHILD_PACS_REPORT_ABNORMAL);
        });
    }

}
